package flexo.file;

import flexo.file.reader.Reader;
import flexo.file.writer.Writer;

/**
 * Represents a file loaded into memory.
 * @author Miguel
 */
public class File
{
	protected Node root;
	
	/**
	 * Creates an empty file. Use the load method to load an actual file
	 * from disk.
	 */
	public File()
	{
		root = new Node("");
	}
	
	/**
	 * Loads a file from disk.
	 * @param fileName the name of the file that will be loaded.
	 */
	public File(String fileName)
	{
		flexo.common.System sys = flexo.Kernel.getSystem(flexo.file.FileSystem.ID);
		if (sys == null)
		{
			flexo.file.FileSystem fs = (flexo.file.FileSystem)sys;
			String fullName = fs.getFullPath(fileName);
			if (fullName != null)
			{
				fileName = fullName;
			}
		}		
		root = new Node(fileName);
	}
	
	/**
	 * @return the root node of the file structure.
	 */
	public Node getRootNode()
	{
		return root;
	}
	
	/**
	 * Sets the name of the file. It won't be saved to disk until you use
	 * the write method.
	 */
	public void setName(String name)
	{
		root.name = name;
	}
	
	/**
	 * @return the name of the file.
	 */
	public String getName()
	{
		return root.name;
	}
	
	/**
	 * Finds a node inside the file hierarchy.
	 * @param name the name of the node you want to find.
	 * @return the node wanted or null if nothing is found.
	 */
	public Node findNode(String name)
	{
		return root.findChild(name);
	}
	
	/**
	 * Saves a file to disk using a Writer.
	 */
	public void save(Writer writer)
	{
		writer.write(root);
	}

	/**
	 * Loads a file from disk using a Reader.
	 */
	public void load(Reader reader)
	{
		reader.read(root);
	}
	
	/**
	 * Returns the name of the file.
	 */
	public String toString()
	{
		return root.toString();
	}
}
